<template>
  <el-dialog
    v-el-drag-dialog
    title="图片上传"
    :visible.sync="visible"
    width="700px"
    append-to-body
  >
    <!-- action="//upload.qiniup.com/"   :on-success="handleSuccess"-->
    <el-upload
      ref="upload"
      multiple
      :data="qiniuData"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :limit="limit"
      :http-request="uploadToQiNiu"
      :on-exceed="handleExceed"
      :file-list="fileList"
      accept="image/jpeg, image/jpg, image/png"
    >
      <el-button size="small" type="primary">选择文件</el-button>
      <div slot="tip" class="el-upload__tip">* 支持上传jpeg、png类型图片，且每张图片不超过3MB。每次最多上传3张。</div>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.upload" type="primary" @click="success">
        开始上传
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { queryQiniuyunUploadToken, querySaveUserAnnexListByPc } from '@/api'
  import * as qiniu from 'qiniu-js'
  import { mapGetters } from 'vuex'
  import watermark from '@/utils/watermark'
  import compress from '@/utils/compress'

  export default {
    name: 'PcUpload',
    data() {
      return {
        visible: false,
        fileList: [],
        id: '',
        limit: 3,
        token: '',
        qiniuData: { // 这里是直接绑定data的值
          key: '', // 图片名字处理
          token: '', // 七牛云token
          data: {},
          bucket: ' '
        }
      }
    },
    computed: {
      ...mapGetters([
        'userInfo'
      ])
    },
    created() {
      this.getQiniuyunUploadToken()
    },
    methods: {
      async open(limit, id) {
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          this.limit = limit
          this.id = id
        })
      },
      // 获取七牛云上传token
      async getQiniuyunUploadToken() {
        const res = await queryQiniuyunUploadToken()
        this.qiniuData.token = res.data
      },
      beforeUpload(file) {
        const key = `${this.userInfo.corpCode}_${new Date().getTime()}_${file.name}`
        this.qiniuData.key = key
        return this.qiniuData
      },
      // 未用到
      uploadToQiNiu(e) {
        const _this = this
        const file = e.file // Blob 对象，上传的文件
        const config = {
          useCdnDomain: true, // 表示是否使用 cdn 加速域名，为布尔值，true 表示使用，默认为 false。
          region: qiniu.region.z0 // 根据具体提示修改上传地区,当为 null 或 undefined 时，自动分析上传域名区域
        }
        const putExtra = {
          fname: this.qiniuData.key, // 文件原文件名
          params: {}, // 用来放置自定义变量
          mimeType: ['image/png', 'image/jpeg', 'image/jpg'] // 用来限制上传文件类型，为 null 时表示不对文件类型限制；限制类型放到数组里： ["image/png", "image/jpeg", "image/gif"]
        }
        this.changeFile(file, function(file) {
          var observable = qiniu.upload(file, _this.qiniuData.key, _this.qiniuData.token, putExtra, config)
          observable.subscribe({
            next: result => {
              // 主要用来展示进度
              // console.log(result)
            },
            error: errResult => {
              // 失败报错信息
              // console.log(errResult)
              _this.$message.error('上传失败')
            },
            complete: result => {
              // 接收成功后返回的信息
              console.log(result)
              _this.fileList.push(result)
            }
          })
        }, function() {
          _this.$message.error('压缩失败')
        })
      },
      changeFile(file, onload, onerror) {
        compress(file, 3 * 1024 * 1024, 2 * 1024 * 1024, function(_file) {
          watermark(_file, '仅供附件上传使用，他用无效', onload, onerror)
        }, onerror)
      },
      handleSuccess(res, file, fileList) {
        this.fileList = fileList
      },
      handleRemove(file, fileList) {
        this.fileList = fileList
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前用户证件附件可继续上传最大张数：${this.limit}张，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      async success() {
        if (this.fileList.length === 0) {
          this.$message.info('请选择文件')
          return
        }
        if (this.fileList.length > this.limit) {
          this.$message.warning(`当前用户证件附件可继续上传最大张数：${this.limit}张`)
          return
        }
        const attList = this.fileList.map(item => {
          return {
            sourceName: item.key.split('.')[0],
            suffix: item.key.split('.')[1],
            url: item.key,
            size: item.fsize
          }
        })
        await querySaveUserAnnexListByPc({
          id: this.id,
          sysAttachmentList: attList
        })
        this.resolve()
        this.visible = false
      }
    }
  }
</script>

<style scoped>

</style>
